package com.retailshop.shopfinace.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.retailshop.shopfinace.common.StringUtil.getStringFormatValueOfObject;



@Aspect
@Component
public class GoodsAspect {

    @Autowired
    private ObjectMapper objectMapper;

    @Pointcut("execution(public * com.retailshop.shopfinace.wapController.*.*(..))")
    public void PointCuts() {
    }


    @Around("PointCuts()")
    public Object log(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Logger logger = LoggerFactory.getLogger(proceedingJoinPoint.getTarget().getClass());
        Object response = null;
        String IP=null;
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

             IP = IpUtil.getIpAddr(request);
            System.out.println("Ip----->" + IP);
            String methodName = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();

            logger.info("进入方法 method({})", methodName);

//            logger.info("--------------------> : " + Arrays.toString(proceedingJoinPoint.getArgs()));
//            logger.info("--------------------> : " + proceedingJoinPoint.getArgs());
            String url = request.getRequestURL().toString();
            logger.info("请求url：" + url);
            logger.info("请求参数：" + request.getQueryString());

            logger.info("Parameters(Args->{})", getStringFormatValueOfObject(objectMapper, proceedingJoinPoint.getArgs()));
            response = proceedingJoinPoint.proceed();
            logger.info("Return({})", response);
            logger.info("返回 method({})", methodName);

        } catch (Throwable throwable) {
            logger.error("Execute error({})", throwable.getMessage());
            throw throwable;
        }
        return response;
    }


}
